<template>
	<div class="app-container">
		<el-form :inline="true" :model="dataForm" @submit.native.prevent @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input placeholder="请输入品名搜索" v-model="dataForm.productName" :clearable="true" size="mini">
          <template slot="prepend">品名</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input placeholder="请输入物料编码搜索" v-model="dataForm.productGmp" :clearable="true" size="mini">
          <template slot="prepend">物料编码</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-select v-model="dataForm.productCategoryId" clearable placeholder="请选择货品种类" size="mini">
			    <el-option
			      v-for="category in categorys"
			      :key="category.productCategoryId"
			      :label="category.productCategoryName"
			      :value="category.productCategoryId">
			    </el-option>
		  	</el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="searchData()" type="primary" class="pan-btn primary-btn" size="mini" icon="el-icon-search">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button v-if="isNoSelect && isAuth('base:product:save')" @click="addModule()" type="success" class="pan-btn success-btn" size="mini" icon="el-icon-upload">新增</el-button>
      </el-form-item>

      <el-form-item>
        <el-button v-if="isNoSelect && isAuth('base:product:delete')" @click="deleteData()" type="danger" class="pan-btn danger-btn" size="mini" icon="el-icon-delete">删除</el-button>
      </el-form-item>
    </el-form>

		<el-table
			:data="dataList"
			v-loading="dataListLoading"
			border
      fit
      highlight-current-row
			@selection-change="selectionChange"
			@row-click="rowClickHandle"
	    style="width: 100%">
    <el-table-column
    	v-if="isNoSelect || isMultiple"
      type="selection"
      header-align="center"
      align="center"
      width="50">
    </el-table-column>
		<el-table-column
			prop="productId"
			header-align="center"
			align="center"
			label="货品编号"
      width="100">
		</el-table-column>
    <el-table-column
    	prop="productCategoryName"
    	header-align="center"
    	align="center"
    	label="货品分类"
      width="100">
    </el-table-column>
		<el-table-column
			prop="productName"
			header-align="center"
			align="center"
			label="品名">
		</el-table-column>
		<el-table-column
			prop="productGmp"
			header-align="center"
			align="center"
			label="物料编码"
      width="100">
		</el-table-column>
		<el-table-column
      v-if="!yfb && !ys"
			prop="productSpec"
			header-align="center"
			align="center"
			label="货品规格">
      <template slot-scope="scope">
        <span v-html='scope.row.productSpec'></span>
      </template>
		</el-table-column>
    <el-table-column
      v-if="!yfb && !ys"
    	prop="productValidity"
    	header-align="center"
    	align="center"
    	label="有效期(单位:月)">
    </el-table-column>
    <el-table-column
      v-if="!yfb && !ys"
    	prop="workshopName"
    	header-align="center"
    	align="center"
    	label="生产车间">
    </el-table-column>
    <el-table-column
    	prop="insideInspectionStandardNum"
    	header-align="center"
    	align="center"
    	label="内控质量标准号">
    </el-table-column>
<!-- 	 <el-table-column
    	prop="pleaseCheckCycle"
    	header-align="center"
    	align="center"
    	label="请验周期">
    </el-table-column>
    <el-table-column
    	prop="samplingCycle"
    	header-align="center"
    	align="center"
    	label="取样周期">
    </el-table-column>
    <el-table-column
    	prop="receivedSampleCycle"
    	header-align="center"
    	align="center"
    	label="收样周期">
    </el-table-column>
    <el-table-column
    	prop="separateSampleCycle"
    	header-align="center"
    	align="center"
    	label="分发周期">
    </el-table-column>
    <el-table-column
    	prop="getCycle"
    	header-align="center"
    	align="center"
    	label="领取周期">
    </el-table-column> -->

    <el-table-column
      prop="createUser"
    	header-align="center"
    	align="center"
    	label="创建人">
    </el-table-column>

    <el-table-column
      prop="createTime"
    	header-align="center"
    	align="center"
    	label="创建时间">
    </el-table-column>

    <el-table-column
      prop="updateUser"
    	header-align="center"
    	align="center"
    	label="操作人">
    </el-table-column>

    <el-table-column
      prop="updateTime"
    	header-align="center"
    	align="center"
    	label="操作时间">
    </el-table-column>

		<el-table-column
				v-if="isNoSelect"
        fixed="right"
        header-align="center"
        align="center"
        label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('base:product:process') && scope.row.productCategoryName == '成品'" type="text" size="small" @click="processData(scope.row)">流程配置</el-button>
          <el-button v-if="isAuth('base:product:upgrade') && (scope.row.haveVersionNumber == 0 || scope.row.haveSupplierNumber == 0)" type="text" size="small" @click="upgrade(scope.row)">升级</el-button>
          <el-button v-if="isAuth('base:product:update')" type="text" size="small" @click="updateData(scope.row)">修改</el-button>
          <el-button v-if="isAuth('base:product:delete')" type="text" size="small" @click="deleteData(scope.row.productId)">删除</el-button>
          <el-button v-if="isAuth('base:product:sync') && scope.row.productGmp != 'H02A'" type="text" size="small" @click="syncData(scope.row)">同步</el-button>
          <template v-if="isAuth('base:product:item') && scope.row.insideInspectionStandardId != null">
            </br>
            <el-button type="text" size="small" @click="setItemMap(scope.row)">配置项目值</el-button>
          </template>
        </template>
      </el-table-column>
		</el-table>
		<el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <el-button v-if="isMultiple" type="primary" class="pan-btn primary-btn" @click="submitMultiple">确 定</el-button>

    <el-dialog
      :title="childDataForm.productName+' 配置项目标准值(内控)'+standard.insideInspectionStandardNum"
      :visible.sync="itemMapVisible"
      :before-close="closeItemMap"
      :close-on-click-modal="false"
      width="50%">
      <el-form size="small">
        <template v-for="(item,itemIndex) of standard.items">
          <el-form-item :key="itemIndex" :label="item.inspectionItemName + ':'">
            <el-row>
              <el-col>
                <div v-html="item.oldValue" />
              </el-col>
            </el-row>
            <el-row style="margin-top: 13px">
              <el-col>
                <el-input type="textarea" :rows="2" v-model="item.insideInspectionItemValue" placeholder="新值" />
              </el-col>
            </el-row>
            <div>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeItemMap">取 消</el-button>
        <el-button type="primary" class="pan-btn primary-btn" @click="submitItemMap">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="同步"
      :visible.sync="syncVisible"
      :before-close="closeSync"
      :close-on-click-modal="false"
      width="80%">
      <el-form label-position="top">
        <el-form-item label="请选择请验日期，从这个时间点开始请验的检验单的货品都更新为当前货品(通过物料编码匹配,同步内容有:货品名称,货品规格)">
          <el-date-picker
            v-model="startTime"
            align="right"
            type="date"
            placeholder="选择日期"
            style="width: 40%;"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
          <el-button icon="el-icon-search" class="pan-btn primary-btn" @click="queryCheckList()"></el-button>
        </el-form-item>

      </el-form>

      <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            :loading="checkListLoading"
            @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="registCheckUserName"
              label="请验人"
              width="180">
            </el-table-column>
            <el-table-column prop="status" header-align="center" align="center" label="状态" width="100">
              <template slot-scope="{row}">
                <el-tag :type="statusFilter(row.status,'type')" size="small">
                  {{ statusFilter(row.status,'name') }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="checkId"
              label="编号"
              width="180">
            </el-table-column>
            <el-table-column
              prop="batchNum"
              label="批号">
            </el-table-column>
          </el-table>
            <el-pagination
              layout="prev, pager, next"
              :total="checkToalPage">
            </el-pagination>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSync">取 消</el-button>
        <el-button type="primary" class="pan-btn primary-btn" @click="submitSync">确 定</el-button>
      </span>
    </el-dialog>

    <product-process
    v-if="processVisible"
    @close="processModule"
    @refreshData="getDataList"
    :childDataForm="childDataForm">
    </product-process>

    <add-or-update-module
    	v-if="addModuleVisible"
    	@close="addModule"
    	@refreshData="getDataList"
    	:childDataForm="childDataForm">
    </add-or-update-module>
	</div>
</template>

<script>

  import {
    mapGetters
  } from 'vuex'

	import {
    getProductList,
    deleteProduct,
    getProductCategorys,
    syncProduct,
    getProductItemMaps,
    saveOrUpdateProductItemMap
  } from "@/api/product"

  import {
    checkList
  } from '@/api/check'



  import { isBlank } from '@/common/js/utils'
	import CommonMethod from '@/views/mixin/common'
	import { CODE_OK } from '@/common/js/config'
	import AddOrUpdateModule from './product-addorupdatemodule'
	import ProductProcess from './product-process'
	export default {
    name: 'huoping',
		props: {
	    isNoSelect: {
	      type: Boolean,
	      default: true
	    },
      grandDataForm: {}
  	},
		mixins: [CommonMethod],
		components: {
			AddOrUpdateModule,ProductProcess
		},
		data() {
    	return {
        tableData:[],
        multipleSelection: [],
        checkListLoading:false,
        syncVisible: false,
        processVisible: false,
	      addModuleVisible: false,
        itemMapVisible: false,
	      dataForm: {
          productName: '',
          productGmp: '',
          productCategoryId: ''
        },
	      dataList: [],
	      categorys: [],
	      pageIndex: 1,
	      pageSize: 10,
	      totalPage: 0,
        checkPageIndex:1,
        checkPageSize:10,
        checkToalPage:0,
	      dataListLoading: false,
	      childDataForm: {},
        standard: {},
	      selectionList: [],
        startTime: '',
        isMultiple: false,
        isStability: false
	    }
  	},
    created() {
      if (!isBlank(this.grandDataForm)) {
        this.dataForm.productCategoryId = this.grandDataForm.checkTypeId
        if (this.grandDataForm.isMultiple) {
          this.isMultiple = this.grandDataForm.isMultiple
        }
        if (this.grandDataForm.productName) {
          this.dataForm.productName = this.grandDataForm.productName
        }
        this.isStability = this.grandDataForm.isStability ? this.grandDataForm.isStability : false
      }
    },
  	mounted() {
  		this.searchData()
  	},
    computed: {
      yfb() {
        if (!isBlank(this.dataForm.productCategoryId)) {
          return this.dataForm.productCategoryId == 1 || this.dataForm.productCategoryId == 2 || this.dataForm.productCategoryId == 3 || this.dataForm.productCategoryId == 9
        }
      },
      ys() {
        return this.dataForm.productCategoryId == 7
      },
      ...mapGetters([
        'userInfo'
      ])
    },
  	methods: {
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      submitItemMap() {
        let items = this.standard.items.filter(it => !isBlank(it.insideInspectionItemValue))
        if (items.length > 0) {
          saveOrUpdateProductItemMap(items).then(res => {
            if (res.code === CODE_OK) {
              this.$message.success('提交成功')
              this.closeItemMap()
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      },
      // setItemMap(row) {
      //   this.childDataForm = JSON.parse(JSON.stringify(row))
      //   const params = {
      //     standardId: row.insideInspectionStandardId,
      //     productId: row.productId
      //   }
      //   getStandardByProductId(params).then(res => {
      //     if (res.code === CODE_OK) {
      //       this.standard = res.standard
      //       this.standard.items = this.standard.items.map(it => {
      //         this.$set(it,'productId',this.childDataForm.productId)
      //         it.insideInspectionStandardId = this.standard.insideInspectionStandardId
      //         this.$set(it,'oldValue',it.insideInspectionItemValue)
      //         it.insideInspectionItemValue = null
      //         it.nationInspectionItemValue = null
      //         return it
      //       })
      //       getProductItemMaps(params).then(res => {
      //         if (res.code === CODE_OK) {
      //           for (let bpim of res.list) {
      //             for (let i=0,j=this.standard.items.length; i<j; i++) {
      //               if (this.standard.items[i].inspectionItemId == bpim.inspectionItemId) {
      //                 this.standard.items[i].insideInspectionItemValue = bpim.insideInspectionItemValue
      //                 this.standard.items[i].nationInspectionItemValue = bpim.nationInspectionItemValue
      //                 break
      //               }
      //             }
      //           }
      //         }else{
      //           this.$message.error(res.msg)
      //         }
      //       })
      //     }else{
      //       this.$message.error(res.msg)
      //     }
      //   })
      //   this.itemMapVisible = true
      // },
      submitMultiple() {
        if (this.grandDataForm.notStandard) {
          this.$emit('clickBtn', this.selectionList)
        }else{
          let products = this.selectionList.filter(p => {return p.insideInspectionStandardNum == null})
          if (products.length == 0) {
            this.$message.error("你选择的所有货品都已经绑定标准")
            return
          }
          if (products.length != this.selectionList.length) {
            this.$message.error("系统已为您自动去掉已经绑定标准的货品")
          }
          this.$emit('clickBtn', products)
        }
      },
      submitSync() {
        if (isBlank(this.startTime)) {
          this.$message.error("请选择一个时间点")
          return
        }
        const data = {
          productId: this.childDataForm.productId,
          startTime: this.startTime
        }
        syncProduct(data).then(res => {
          if (res.code === CODE_OK) {
          	this.$message.success("同步成功")
            this.closeSync()
          }else{
          	this.$message.error(res.msg)
          }
        })
      },
      closeSync() {
        this.syncVisible = false
      },
      closeItemMap() {
        this.childDataForm = ''
        this.itemMapVisible = false
      },
      syncData(row) {
        this.childDataForm = JSON.parse(JSON.stringify(row))
        this.syncVisible = true
      },
      upgrade(row) {
        this.$set(row,'isUpgrade',true)
        // 判断是版本号升级还是供应商代号升级
        if (row.haveVersionNumber == 0) {
          row.productGmp = row.productGmp.substring(0,row.productGmp.length - 2)
          let oldNumber = row.versionNumber
          let newNumber = parseInt(oldNumber) + 1
          newNumber = ('00' + newNumber).slice(-2)
          row.versionNumber = newNumber
          row.productGmp = row.productGmp + newNumber
        }else{
          row.productGmp = row.productGmp.substring(0,row.productGmp.length - 1)
          let oldNumber = row.supplierNumber
          let newNumber = String.fromCharCode(oldNumber.charCodeAt(0) + 1)
          row.supplierNumber = newNumber
          row.productGmp = row.productGmp + newNumber
        }
        this.childDataForm = JSON.parse(JSON.stringify(row))
        this.addModuleVisible = true
      },
      processData(row) {
        this.childDataForm = row
        this.processVisible = !this.processVisible
      },
  		rowClickHandle(row) {
      	if (!this.isNoSelect) {
        	this.$emit('clickRow', row)
      	}
    	},
      processModule() {
        this.childDataForm = ""
        this.processVisible = !this.processVisible
      },
  		addModule() {
  			this.childDataForm = ""
  			this.addModuleVisible = !this.addModuleVisible
  		},
  		searchData() {
        if (this.isAuth('base:product:list') || !this.isNoSelect){
          this.pageIndex=1
        	this.getDataList()
        }
  		},
			getDataList() {
	  		this.dataListLoading = true
	  		const params = {
	        page: this.pageIndex,
	        limit: this.pageSize,
	        productName: this.dataForm.productName || null,
	        productGmp: this.dataForm.productGmp || null,
	        productCategoryId: this.dataForm.productCategoryId || null
	      }
	  		getProductList(params).then(res => {
	  			if (res.code === CODE_OK) {
	  				this.dataList = res.page.list
            if (this.dataList.length == 0) {
              this.$message({
                message: '系统提示您：此货品在资料库中不存在，请试着修改搜索条件',
                type: 'error',
                duration: 3000
              })
            }
	  				this.totalPage = res.page.totalCount
	  			}else{
	  				this.$message.error(res.msg)
	  			}
	  			this.dataListLoading = false
	  		}).catch({})
        getProductCategorys().then(res => {
        	if (res.code === CODE_OK) {
        		this.categorys = res.categorys
        	}
        })
			},
			updateData(row) {
				this.childDataForm = row
				this.addModuleVisible = !this.addModuleVisible
			},
			deleteData(id) {
				if (this.selectionList.length == 0 && id == undefined) {
					this.$message.error('请选择至少一个货品')
					return
				}
				let ids = id ? [id] : this.selectionList.map(item => {
					return item.productId
				})
				let msg = id ? '此操作将永久删除此货品, 是否继续?' : '此操作将永久删除选中的货品, 是否继续?'
				this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
       	}).then(() => {
       		deleteProduct(ids).then(res => {
       			if (res.code === CODE_OK) {
       				this.$message({
		            type: 'success',
		            message: '删除成功!'
		          })
       				this.getDataList()
       			}else{
       				this.$message.error(res.msg)
       			}
       		})
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
			},
			selectionChange(obj) {
				this.selectionList = obj
			},
      queryCheckList(){
        this.checkListLoading = true;
        //获得具体时间，具体货品的请验单列表
        const params = {
          page: this.pageIndex,
          limit: this.pageSize,
          status: '1,2,3,4,5,6,10,7,8,11',
          productGmp: this.childDataForm.productGmp,
          startTime: this.startTime,
          endTime: this.startTime,
          createUserId: this.userInfo.userId
        }
        checkList(params).then(res => {
        	if (res.code === CODE_OK) {
        		this.tableData = res.page.list;
        		this.checkToalPage = res.page.totalCount;
        	}else{
        		this.$message.error(res.msg)
        	}
        	this.checkListLoading = false
        }).catch()
      },
      statusFilter(status, val) {
        const statusMap = {
          0: {
            name: '待处理',
            type: 'danger'
          },
          1: {
            name: '待取样',
            type: 'primary'
          },
          2: {
            name: '待收样',
            type: 'warning'
          },
          3: {
            name: '待分发',
            type: 'warning'
          },
          4: {
            name: '检验中',
            type: 'warning'
          },
          5: {
            name: '检验中',
            type: 'warning'
          },
          6: {
            name: '待结论',
            type: 'warning'
          },
          10: {
            name: '待放行',
            type: 'success'
          },
          7: {
            name: '待放行',
            type: 'success'
          },
          8: {
            name: '待确认',
            type: 'success'
          },
          11: {
            name: '已完成',
            type: 'success'
          }
        }
        return statusMap[status][val]
      }
  	}
	}
</script>

<style scoped>
  >>> .el-form-item__content {
    line-height: normal;
  }
</style>
